// pages/address/list.js
import { getUserAddrs, deleteUserAddr } from '../../utils/apis'
import { confirm } from '../../utils/util'
const app = getApp()
Page({
  data: {
    page: 0,
    size: 10
  },
  onLoad: function(options) {
    // 页面初始化 options为页面跳转所带来的参数
    this.loadData()
  },

  onPullDownRefresh() {
    this.loadData(function() {
      wx.stopPullDownRefresh()
    })
  },
  loadData(cb) {
    var that = this
    var { loading } = this.data
    if (loading) {
      return
    }
    this.setData({
      loading: true
    })
    wx.showNavigationBarLoading()
    app.getLoginInfo(loginInfo => {
      if (!loginInfo) {
        return alert('用户未登录')
      } else {
        getUserAddrs()
          .then(result => {
            that.setData({
              list: result,
              loading: false
            })
            wx.hideNavigationBarLoading()
            cb && cb()
          })
          .catch(err => {
            that.setData({
              loading: false
            })
            wx.hideNavigationBarLoading()
            cb && cb()
          })
      }
    })
  },
  callback() {
    this.loadData()
  },
  onDelete(e) {
    var that = this
    var { id } = e.currentTarget
    var address = this.data.list[id]
    confirm({
      content: `是否删除地址 ${address.areaName} ${address.addressDetail}`,
      confirmText: '删除',
      ok() {
        deleteUserAddr({
          id: address.id
        })
          .then(result => {
            that.data.list.splice(id, 1)
            that.setData({
              list: that.data.list
            })
          })
          .catch(err => {})
      }
    })
  }
})
